
<template>
  <div class="chat-view">
    <div class="chat-record">
      <div v-for="item in chatRecord" class="chat-item" :class="{ 'is-self': item.sender === 'self' }">
        <span>{{ item.msg }}</span>
        <span>{{ item.date }}</span>
      </div>
    </div>
    <div class="handler-bar">
      <input type="text" v-model="text" @keyup.enter="sendText">
      <button @click="sendText">发送</button>
      <button @click="chatRecord = []">清空</button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { io } from 'socket.io-client';
import { ref, onMounted } from 'vue';

const chatRecord = ref()
chatRecord.value = []
const text = ref('')

const socket = io('ws://139.155.86.10:3366');
const sendText = () => {
  chatRecord.value.push({
    msg: text.value,
    date: new Date().toLocaleString(),
    sender: 'self'
  })
  socket.emit('sendText', { msg: text.value })
  text.value = ''
}
socket.on('sendText', (data) => {
  console.log(data)
  chatRecord.value.push({ msg: data.msg, date: new Date().toLocaleString() })
});

onMounted(() => {
  socket.connect(); //连接socket服务器
});


</script>

<style lang="scss">
.chat-view {
  max-width: 500px;
  margin: 0 auto;
  padding-top: 10vh;

  .handler-bar {
    text-align: center;
    margin-top: 20px;

    button {
      margin-left: 10px;
    }
  }
}

.chat-record {
  border: 1px dashed #999;
  border-radius: 5px;
  height: 30vh;
  overflow-y: auto;
  padding: 20px;
}

.chat-item {
  margin-right: 100px;
  display: flex;
  justify-content: space-between;
  padding-bottom: 5px;
  text-align: left;
  border: 2px solid cadetblue;
  border-radius: 10px;
  padding: 10px;
  position: relative;
  margin-bottom: 10px;

  &::before {
    content: " ";
    position: absolute;
    right: 100%;
    top: 50%;
    margin: -5px 0 0;
    border: 10px solid transparent;
    border-right-color: cadetblue;
  }

  &::after {
    content: " ";
    position: absolute;
    right: 100%;
    top: 50%;
    margin-top: -2px;
    border: 7px solid transparent;
    border-right-color: #fff;
  }

  &.is-self {
    margin-right: 0;
    margin-left: 100px;

    &::before {
      content: " ";
      position: absolute;
      left: 100%;
      top: 50%;
      margin: -5px 0 0;
      border: 10px solid transparent;
      border-left-color: cadetblue;
    }

    &::after {
      content: " ";
      position: absolute;
      left: 100%;
      top: 50%;
      margin-top: -2px;
      border: 7px solid transparent;
      border-left-color: #fff;
    }
  }
}
</style>
